﻿﻿// Hello World! example user script
//具备私信发送功能
//调用微博界面的私信发送按钮
//私信用户从服务器加载
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.  To install it, you need
// Greasemonkey 0.3 or later: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "Hello World", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==UserScript==
// @name          Wei Bo Messenger
// @namespace     http://WeiboRobs.com
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require       http://stjack.no-ip.org:8081/WebTruth/scripts/msg.js
// @description   example script to alert "Hello world!" on every page
// Features
// @include       http://t.qq.com/*
// @exclude       http://WeiboRobs.com/*
// @exclude       http://WeiboRobs.com/*
// ==/UserScript== 
//////////////////////////////////////////////////////////////////


var mouseX,mouseY=0;
var user,pass;																					         //用户名和密码，从server获取
var loginTime=new Date().getTime();											         //获取登录时的时间，翻页的时候比较下，是否超时
var verifyCodeFlag=false;                                        //flag=true表示发现了验证码，需要执行验证码的WebSocket请求
var verifyUUID='';                                               //校驗碼UUID
var xmlhttptURL =  "http://stjack.no-ip.org:8081/WebTruth/weibo";

var offX=window.screenX;
var offY=window.screenY;
var msgInteval=25*1000;                                           //发送2条私信之间的间隔时间=15秒
var truthText="";
var globalLimit=15;
//var offY=145;//FF的document距离屏幕上方的距离，不同分辨率有细微的区别
var offY=105;   //windows 2008的值=86!win7=86, 108=chinku 


	var href=document.location.href;
	console.log(href);
	if(href=="http://t.qq.com/" || href=="t.qq.com" || href.indexOf('http://t.qq.com/login.php')>0){
		   console.log('href:=',href);
	}else{
		mainWeibo();	
	}
	
	//获取一条真相msg
	function getTruthMsg(){
	   var idxText=Math.abs((getSystemTime()+1) % trueMessages.length) ;//trueMessages在msg.js文件中
	   console.log('truthText：',idxText,trueMessages[0],Date());
	   truthText=trueMessages[idxText];
	   console.log('truthText：',trueMessages[idxText],truthText,idxText,Date());
	}

	function mainWeibo(){
	  try{
		   console.log('mainWeibo: 页面跳转到私信发送界面！',window.screenX,window.screenY,window.pageYOffset,window.pageXOffset,Date(),window.location.href);
	       document.location.href='http://t.qq.com/messages/inbox#pmtid=';
		   //从缓存加载真相文件
	  	   //getAllTruthMessage();
	 
		 	 
	       //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
		   //创建verifyUUID
		   console.log('登陆后页面发生跳转，会清除全部保留在页面的js变量的值');
		   if(GM_getValue("verifyUUID")!=null){
		   	  verifyUUID=GM_getValue("verifyUUID");
		   	  console.log('GM_getValue: verifyUUID=',verifyUUID);
		   }else{
		   	  verifyUUID=randomUUID();
			  GM_setValue("verifyUUID",verifyUUID);
		   	  console.log('GM_setValue: verifyUUID=',verifyUUID);
		   }
		   
	     
	  	   //获取私信用户!
		   window.setTimeout(function(){
		      getPSNMesseger();
		   },15*1000);
	       console.log(document.body.clientWidth+'--'+document.body.clientHeight);
					 

	  }catch(e) {console.log('control code area:',e.message,Date());}	
	}

//\\//\\//\\//\\//\\//\\//\\//\\//\\No.9 处理验证码标志位变化//\\//\\//\\//\\//\\//\\//\\//\\//\\
    var verifyCodeFlagChange=(function(){
		var verifyCodeFlag=false;
		return {
			  getverifyCodeFlag:function(){
			  	  return verifyCodeFlag;
			  },
				setverifyCodeFlag:function(a){
					 verifyCodeFlag=a;
           if(verifyCodeFlag){
           	  verifyValidXMLHttp(verifyCodeFlag);
					    console.log('setverifyCodeFlag : verifyCodeFlag==',verifyCodeFlag, Date());
					 	  return;
					 }else{
					    console.log('setverifyCodeFlag : verifyCodeFlag==',verifyCodeFlag, Date());
					 }
				}
		}
    }());
//\\//\\//\\//\\//\\//\\//\\//\\//\\No.10 3天内不重复发送数据 - google 服务器校验//\\//\\//\\//\\//\\//\\//\\//\\//\\
	var weiboUsrVerify=(
	   function(){
	   	  try{
				var weiboUsrVerifyFlag='N';
				return {
					  getweiboUsrVerify:function(){
					  	return weiboUsrVerifyFlag;
					  },
						setweiboUsrVerify:function(a){
							 weiboUsrVerifyFlag=a;
						}
				}
		  }catch(e) {console.log('weiboUsrVerify:',e.message,Date());}	
	 }());



function sendToLocalXMLHttp(jsonString){
	console.log('sendToLocalXMLHttp: 向服务器发送登出的xmlhttp请求',new Date());
	try{
	   GM_xmlhttpRequest({
		   method: "POST",
		   url: "http://127.0.0.1:9988/weibo",
		   data:jsonString, 
		   synchronous:false, 
		   headers: {
			     "User-Agent": "Mozilla/5.0",     
			     "Accept": "text/xml",            
			     "Content-Type": "application/x-www-form-urlencoded "
		   },
	       onreadystatechange: function(response) {
	       	   if(response.readyState==4 ){
		           var jsonString =response.responseText;
				   console.log('sendToLocalXMLHttp: onreadystatechange 函数开始填充从服务器获取的真相信息！',jsonString,Date());
	       	   }
	       },
		   onload: function(response) {
      	       var jsonString =response.responseText;
			   console.log('sendToLocalXMLHttp: onload函数开始填充从服务器获取的真相信息！',jsonString,Date());
		   },
		   onerror: function(response) {
			   console.log('sendToLocalXMLHttp: onerror',response);
		   },
		   ontimeout: function(response) {
			   console.log('sendToLocalXMLHttp:ontimeout',response);
		   }
	   });	
	}catch(e) {console.log('sendToLocalXMLHttp:',e.message,Date());}		 
}



//\\//\\//\\//\\//\\//\\//\\//\\//\\发送请求，获取私信用户//\\//\\//\\//\\//\\//\\//\\//\\//\\
var msgAcct=null;//私信用户的账号
function getPSNMesseger(){
    console.log('getPSNMesseger 发送请求，获取私信用户:',Date());  
    var datas=[];
		
	var data = {};

	data["id"] ='00000';
	data["subProtocol"] = 'msgRobot';
	data["remoteIPAddress"] = '0.0.0.0';
	data["remotePort"] = '0';
	data["agent"] = '';
	data["responseCommand"] = '';
	data["requestCommand"] = 'getMessenger';
	data["responseTime"] = '0';
		
	data["requestTime"] = getSystemTime()+'';
	data["base64Image"] = '000';
	data["base64ImageFlag"] ='0';
	datas.push(data);
	var jsonString = JSON.stringify(datas);        
	console.log(jsonString);
	
	var idx=Math.abs((getSystemTime()+1) % 100);//2%的比例向测试帐号allison1975发送信息
	try{
	  	GM_xmlhttpRequest({
	  	   method: "POST",
	  	   url: xmlhttptURL,
	  	   data:jsonString, 
	  	   synchronous:false, 
	  	   headers: {
	  	     "User-Agent": "Mozilla/5.0",     
	  	     "Accept": "text/xml",            
	  	     "Content-Type": "application/x-www-form-urlencoded "
	  	   },
	  	   onreadystatechange: function(response) {
	  	   	  if(response.readyState==4 ){
       	        var jsonString =response.responseText;
	  	   	      console.log('getPSNMesseger: onload函数开始填充从服务器获取的真相信息！',jsonString,Date());
	  	   	      var jsonObj=JSON.parse(jsonString);
	  	   	      if(jsonObj[1]==null || idx==1){
	  	   	    	msgAcct='allison1975';
	 	  		  }else if(jsonObj[1]==null || idx==51){
	 	  			msgAcct='g_tmy1975';
	 	  		  }else{
	 	  			msgAcct= jsonObj[1];
	 	  		  }
	  	   	      
	  	   	      getTruthMsg();
	  	   	      console.log("getPSNMesseger: 开始发送真相消息",truthText);
	  	   	      
	  	    	  var msg= document.evaluate(		
				    	  "//div[@class='heading']/a",
					        document,    
					        null,    
					        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
					        null).snapshotItem(0);
	  	    	  console.log("getPSNMesseger: msg按钮",msg);
	  	    	  if(msg==null || msg=='undefined'){
	  	 	          document.location.href='http://t.qq.com/messages/inbox#pmtid=';
	  	    	  }else{
	  	    		 $(msg).click();
	  	    		 window.setTimeout(function(){
		  	   	        personalMsgSend(msgAcct,truthText);
	  	    		 },5000); 
	  	    	  }
	  	   	  }//readyState==4
	  	   },
	  	   onload: function(response) {
	  	   	//console.log('getPSNMesseger: onerror',response);
	  	   },
	  	   onerror: function(response) {
	  	   	//console.log('getPSNMesseger: onerror',response);
	  	   },
	  	   ontimeout: function(response) {
	  	   	//console.log('getPSNMesseger:ontimeout',response);
	  	   }
	  	});	
	  }catch(e) {console.log('getPSNMesseger:',e.message,Date());}		 
}



  var sndBtnPosX=0;
  var sndBtnPosy=0;
  var sndTextPosX=0;
  var sndTextPosY=0;
  var sndImgPosX=0;
  var sndImgPosY=0;
  var receiverPosX=0;
  var receiverPosY=0;
  /**
   * personalMsgSend：发送私信函数
   *  msgAcct: 收信人ID
    * truthText : 真相文本**/
  function personalMsgSend(msgAcct,truthText){
	    console.log('personalMsgSend私信发送 begin !');
	    try{
	    	var xPos=0;var yPos=0;
	    	var sndTextPos=null;
	    	var sndImg=null;
	    	var receiver  = document.evaluate(	//收信人	
				    	  "//textarea[@id='wbpmcomposedlgto']",
				        document,    
				        null,    
				        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
				        null).snapshotItem(0);
			var receiverPos= getElementAbsolutePos(receiver);
			xPos=Math.floor(receiverPos.x+10);
			yPos=Math.floor(receiverPos.y-window.pageYOffset+offY+5);
		    if(xPos<=100 || yPos<=100){
		    	xPos=receiverPosX;
		    	yPos=receiverPosY;
		    	
		    }else{
		    	receiverPosX=xPos;
		    	receiverPosY=yPos;
		    }
			jsonString = 'action=clickPosWithMsg&xPos='+xPos+'&yPos='+yPos+'&msg='+msgAcct;        
		    console.log('personalMsgSend私信发送: 向本地服务器发送指令，模拟硬件点击，发送消息到FF的对话框',jsonString);
			sendToLocalXMLHttp(jsonString);
		    //发送文本框
			var sndText= document.evaluate(		
				    	  "//div[@class='D']/descendant::textarea[@id='wbpmcomposedlgeditor']",
				        document,    
				        null,    
				        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
				        null).snapshotItem(0);
		    $(sndText).bind('click',function(e){
	            console.log('personalMsgSend私信发送: 文本信息已经paste了： 开始click图片upload按钮！');
	            window.setTimeout(function(){
	            	//
	    			var sndImgPos= getElementAbsolutePos(sndImg);
	    			console.log('personalMsgSend---sndImg当前的坐标系是：',sndImgPos.x,sndImgPos.y-window.pageYOffset+offY);
	    			xPos=Math.floor(sndImgPos.x+10);
	    			yPos=Math.floor(sndImgPos.y-window.pageYOffset+offY+5);
				    if(xPos<=100 || yPos<=100){
				    	xPos=sndImgPosX;
				    	yPos=sndImgPosY;
				    	document.location.reload(true);
				    }else{
				    	sndImgPosX=xPos;
				    	sndImgPosY=yPos;
				    }
	    			var jsonString = 'action=clickPosImg&xPos='+xPos+'&yPos='+yPos;  
	    			console.log('personalMsgSend---jsonString：',jsonString);
	    			sendToLocalXMLHttp(jsonString);
	            },1500);
            });
				    
					
				//发送插入图片按钮 	
			sndImg= document.evaluate(		
						"//div[@class='D']/descendant::a[@class='wbpmimg inserticon']",
						document,    
						null,    
					    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
						 null).snapshotItem(0);
			//真正的文件上传按钮！
			var upload=document.evaluate(		
					"//input[@class='wbpmimgfile' and @type='file']",
					document,    
					null,    
				    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
					 null).snapshotItem(0);
			console.log('personalMsgSend私信发送:  插入图片按钮 sndImg',upload);
			$(upload).bind('change',function(e){	
				window.setTimeout(function(){
					var sndBtn= document.evaluate(		
							    "//div[@class='D']/descendant::a[@id='wbpmcomposedlgsend']",
							    document,    
							    null,    
							    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
							    null).snapshotItem(0);
					console.log('personalMsgSend私信发送:  发送按鈕sndBtn',sndBtn);
					var sndBtnPos= getElementAbsolutePos(sndBtn);
					console.log('personalMsgSend---sndBtn当前的坐标系是：',sndBtnPos.x,sndBtnPos.y-window.pageYOffset+offY);
						
					xPos=Math.floor(sndBtnPos.x+10+window.screenX );
					yPos=Math.floor(sndBtnPos.y-window.pageYOffset+offY+10);
				    if(xPos<=100 || yPos<=100){
				    	document.location.reload(true);
				    	xPos=sndBtnPosX;
				    	yPos=sndBtnPosY;
				    }else{
				    	sndBtnPosX=xPos;
				    	sndBtnPosY=yPos;
				    }
					jsonString = 'action=clickPos&xPos='+xPos+'&yPos='+yPos;  
					console.log('personalMsgSend---jsonString开始真正的私信发送：',jsonString);
					sendToLocalXMLHttp(jsonString);
					//在upload图片上传按钮触发15秒以后，检查私信发送按钮是否存在，存在说明
					//私信发送失败，登出系统
					window.setTimeout(function(){
					    try{
							//发送文本框
							var sndText= document.evaluate(		
								    	  "//div[@class='D']/descendant::textarea[@id='wbpmcomposedlgeditor']",
								        document,    
								        null,    
								        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
								        null).snapshotItem(0);
							if(sndText!=null && sndText!='undefined'){
								console.log('personalMsgSend私信发送failed!');
							    window.setTimeout(function(){
								   logOutAndHangupADSL();//登出系统
							    },15000);//等待5秒登出
							}
					    }catch(e) {
					    	console.log('personalMsgSend私信发送成功了!');
					    }	
						globalLimit--;
						console.log('personalMsgSend---globalLimit：',globalLimit);
						if(globalLimit<=0){
						    window.setTimeout(function(){
							   logOutAndHangupADSL();//登出系统
						    },15000);//等待5秒登出
						}
							
						getTruthMsg();//生成一条新的真相消息
						getPSNMesseger();
					},msgInteval);
				},5000);//等待5秒上传文件
			});	
			//真正开始发送信息！然后再开始触发上面的事件！
			sndTextPos= getElementAbsolutePos(sndText);
			//计算发送文本框的坐标位置
			xPos=Math.floor(sndTextPos.x+20+window.screenX );
			yPos=Math.floor(sndTextPos.y-window.pageYOffset+offY+15);
		    if(xPos<=100 || yPos<=100){
		    	//document.location.reload(true);
		    	xPos=sndTextPosX;
		    	yPos=sndTextPosY;
		    }else{
		    	sndTextPosX=xPos;
		    	sndTextPosY=yPos;
		    }
			jsonString = 'action=clickPosWithMsg&xPos='+xPos+'&yPos='+yPos+'&msg='+truthText;        
		    console.log('personalMsgSend私信发送: 向本地服务器发送指令，Java Server模拟硬件点击，发送消息到FF的对话框',jsonString);
			sendToLocalXMLHttp(jsonString);

			var closeBtn= document.evaluate(		
					    		"//div[@class='D']/descendant::div[@class='DWrap']/a[@class='DClose close']",
					    	    document,    
					    	    null,    
					    	    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
					    	    null).snapshotItem(0);    
		
				console.log('personalMsgSend私信发送:  监控字符的输入，如果输入了回车字符，表示文本输入结束了，等待0.5秒后点击发送按钮！');
				var closeBtnPos= getElementAbsolutePos(closeBtn);
				console.log('personalMsgSend---closeBtn当前的坐标系是：',closeBtnPos.x,closeBtnPos.y-window.pageYOffset+offY);
				//$(closeBtn).click();
				    //Test code!!!!
				//personalMsgSend();
					
	    }catch(e) {
	    	console.log('personalMsgSend私信发送:',e.message,Date());
	    }	
  }




function checkSendBtn(){
   try{
	   console.log('checkSendBtn： 检查send 私信的按钮是否存在？!',e.message,verify);
	   var sndText= document.evaluate(		
		    	  "//div[@class='talkWrap bgr3']/div[@class='cont']/textarea",
		        document,    
		        null,    
		        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
		        null).snapshotItem(0);
	   if(sndText==null || sndText=='undefined'){
		   return false;
	   }else{
		   return true;
	   }
    }catch(e){
         console.log('checkSendBtn： exception!',e.message);
         return false;   
    }
    
}

 


//\\//\\//\\//\\//\\//\\//\\//\\//\\No.10 3天内不重复发送数据 - google 服务器校验//\\//\\//\\//\\//\\//\\//\\//\\//\\
//No.3,No.4处理服务器自动登出Logout的请求
function logOutAndHangupADSL(){
   try{

	 	 var usrLogin= document.evaluate(		
	 			"//li[@id='topNav1']/a[contains(@class,'txt')]/u",
	 	     document,    
	 	     null,    
	 	     XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
	 	     null).snapshotItem(0);
	 	 	console.log('logOut: ',usrLogin);
	 	 if(usrLogin==null || usrLogin=='undefined'){
	 	 	  console.log('logOut: 用户已经登出qq微薄了！',usrLogin);
	 	 	  return;
	 	 }   
	 	 else{
	 	     var login=usrLogin; 
	 	     var targetX=getElementLeft(login);
	 	     var targetY=getElementTop(login);
	 	     console.log('logOut: ',targetX,targetY,login);   
	  	     $(login).simulate("mouseover", { dx: targetX, dy: targetY });
	         window.setTimeout(function(){
	 	 		 var outBtn= document.evaluate(		
	 	 		 	 "//li/a[@href='http://t.qq.com/logout.php']",
	 	 		      document,    
	 	 		      null,    
	 	 		      XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,    
	 	 		      null).snapshotItem(0);
	 	 	     var tx=getElementLeft(outBtn);
	 	 	     var ty=getElementTop(outBtn);
	             $(outBtn).simulate("mouseover", { dx: tx, dy: ty });
	             var jsonString = 'method=CleanHistory';        
			     console.log('CleanHistory',jsonString);
				 sendToLocalXMLHttp(jsonString);
				 window.setTimeout(function(){
					 outBtn.click();
				 },5000);//等待25秒登出
	         },2000);	
	 	 }
   }catch(e) {
   	   console.log('logOut：异常',e.message);
   }	
}
function weiboLogging(logStr){
    console.log('weiboLogging: 把日志信息发送到服务器端 :',Date());  
	    
		  var datas=[];
	    
		  var data = {};
		  if(verifyUUID==null || verifyUUID=='undefined'){
		     console.log('weiboLogging: Verify Code Validation 心跳连接Exception :verifyUUID==null',Date()); 
		  }else{
		  	 data["id"] =verifyUUID;
		  }
		  data["subProtocol"] = 'robert';
		  data["remoteIPAddress"] = '0.0.0.0';
		  data["remotePort"] = '0';
		  data["agent"] = '';
		  data["responseCommand"] = '';
		  data["requestCommand"] = 'weiboLogging';
		  data["responseTime"] = '0';
		  
		  data["requestTime"] = getSystemTime()+'';
		  data["base64Image"] = logStr;
		  data["base64ImageFlag"] ='0';
		  datas.push(data);
		  var jsonString = JSON.stringify(datas);        
		  console.log(jsonString);
    console.log('weiboLogging: 实际发送 Verify Code Validation 心跳连接:',Date());  
      try{
      	GM_xmlhttpRequest({
      	   method: "POST",
      	   url: xmlhttptURL,
      	   data:jsonString, 
      	   synchronous:false, 
      	   headers: {
      	     "User-Agent": "Mozilla/5.0",     
      	     "Accept": "text/xml",            
      	     "Content-Type": "application/x-www-form-urlencoded "
      	   },
      	   onreadystatechange: function(response) {
      	   	  if(response.readyState==4 ){
       	        var jsonString =response.responseText;
      	   	      console.log('weiboLogging: onload函数开始填充从服务器获取的真相信息！',jsonString,Date());
      	   	  }
      	   },
      	   onload: function(response) {
      	   	console.log('weiboLogging: onerror',response);
      	   },
      	   onerror: function(response) {
      	   	console.log('weiboLogging: onerror',response);
      	   },
      	   ontimeout: function(response) {
      	   	console.log('weiboLogging:ontimeout',response);
      	   }
      	});	
      }catch(e) {console.log('weiboLogging:',e.message,Date());}		 
}

function simulateKeyEvent(target, keyCode) {
	try {

	    if (!target) {
	    	console.log("Target is not exist");
	    }
      
	    var customEvent = null;
	    var a = typeof document.createEvent;
      
	    if (typeof document.createEvent == "function") {
      
	    		//firefox
	    		customEvent = document.createEvent("KeyEvents");
	    		customEvent.initKeyEvent("keypress", true, true, window, false, false, false, false, keyCode, keyCode);
	    	  target.dispatchEvent(customEvent);
      
	    } else if (document.createEventObject) { //IE
      
	    	customEvent = document.createEventObject();
      
	    	customEvent.bubbles = true;
	    	customEvent.cancelable = true;
	    	customEvent.view = window;
	    	customEvent.ctrlKey = false;
	    	customEvent.altKey = false;
	    	customEvent.shiftKey = false;
	    	customEvent.metaKey = false;
	    	customEvent.keyCode = keyCode;
      
	    	target.fireEvent("onkeypress", customEvent);
      
	    } else {
	    	console.log("This example is only demonstrating event simulation in firefox and IE.");
	    }

	} catch (ex) {
			console.log("Shit happends. This example is only demonstrating event simulation in firefox and IE.");
	}
}

/*获取页面元素的y坐标*/
function getElementTopNew(element){
   var actualTop = element.offsetTop;
   var current = element.offsetParent;

   while (current != null){
	   if ( element.style.position == 'absolute' || element.style.position == 'relative' 
           || ( element.style.overflow != 'visible' && element.style.overflow != '' ) )
       {
           break;
       }  
	   actualTop += current.offsetTop;
      current = current.offsetParent;
   }
  return actualTop;
}


function __getIEVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function __getOperaVersion() {
    var rv = 0; // Default value
    if (window.opera) {
        var sver = window.opera.version();
        rv = parseFloat(sver);
    }
    return rv;
}
//http://www.codeproject.com/Articles/35737/Absolute-Position-of-a-DOM-Element#
var __userAgent = navigator.userAgent;
var __isIE =  navigator.appVersion.match(/MSIE/) != null;
var __IEVersion = __getIEVersion();
var __isIENew = __isIE && __IEVersion >= 8;
var __isIEOld = __isIE && !__isIENew;

var __isFireFox = __userAgent.match(/firefox/i) != null;
var __isFireFoxOld = __isFireFox && ((__userAgent.match(/firefox\/2./i) != null) || 
	(__userAgent.match(/firefox\/1./i) != null));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;

var __isWebKit =  navigator.appVersion.match(/WebKit/) != null;
var __isChrome =  navigator.appVersion.match(/Chrome/) != null;
var __isOpera =  window.opera != null;
var __operaVersion = __getOperaVersion();
var __isOperaOld = __isOpera && (__operaVersion < 10);

function __parseBorderWidth(width) {
    var res = 0;
    if (typeof(width) == "string" && width != null && width != "" ) {
        var p = width.indexOf("px");
        if (p >= 0) {
            res = parseInt(width.substring(0, p));
        }
        else {
     		//do not know how to calculate other values 
		//(such as 0.5em or 0.1cm) correctly now
    		//so just set the width to 1 pixel
            res = 1; 
        }
    }
    return res;
}

//returns border width for some element
function __getBorderWidth(element) {
	var res = new Object();
	res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
	if (window.getComputedStyle) {
		//for Firefox
		var elStyle = window.getComputedStyle(element, null);
		res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));  
		res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));  
		res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));  
		res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));  
	}
	else {
		//for other browsers
		res.left = __parseBorderWidth(element.style.borderLeftWidth);
		res.top = __parseBorderWidth(element.style.borderTopWidth);
		res.right = __parseBorderWidth(element.style.borderRightWidth);
		res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
	}
   
	return res;
}

//returns the absolute position of some element within document
function getElementAbsolutePos(element) {
	var res = new Object();
	res.x = 0; res.y = 0;
	if (element !== null) { 
		if (element.getBoundingClientRect) {
			var viewportElement = document.documentElement;  
 	        var box = element.getBoundingClientRect();
		    var scrollLeft = viewportElement.scrollLeft;
 		    var scrollTop = viewportElement.scrollTop;

		    res.x = box.left + scrollLeft;
		    res.y = box.top + scrollTop;

		}
		else { //for old browsers
			res.x = element.offsetLeft;
			res.y = element.offsetTop;

			var parentNode = element.parentNode;
			var borderWidth = null;

			while (offsetParent != null) {
				res.x += offsetParent.offsetLeft;
				res.y += offsetParent.offsetTop;
				
				var parentTagName = 
					offsetParent.tagName.toLowerCase();	

				if ((__isIEOld && parentTagName != "table") || 
					((__isFireFoxNew || __isChrome) && 
						parentTagName == "td")) {		    
					borderWidth = kGetBorderWidth
							(offsetParent);
					res.x += borderWidth.left;
					res.y += borderWidth.top;
				}
				
				if (offsetParent != document.body && 
				offsetParent != document.documentElement) {
					res.x -= offsetParent.scrollLeft;
					res.y -= offsetParent.scrollTop;
				}


				//next lines are necessary to fix the problem 
				//with offsetParent
				if (!__isIE && !__isOperaOld || __isIENew) {
					while (offsetParent != parentNode && 
						parentNode !== null) {
						res.x -= parentNode.scrollLeft;
						res.y -= parentNode.scrollTop;
						if (__isFireFoxOld || __isWebKit) 
						{
						    borderWidth = 
						     kGetBorderWidth(parentNode);
						    res.x += borderWidth.left;
						    res.y += borderWidth.top;
						}
						parentNode = parentNode.parentNode;
					}    
				}

				parentNode = offsetParent.parentNode;
				offsetParent = offsetParent.offsetParent;
			}
		}
	}
    return res;
}